package com.StarStudio.Controller;


import com.StarStudio.Service.GoodsService;
import com.StarStudio.Service.PanicBuyingGoodsService;
import com.StarStudio.Service.PanicBuyingOrdersService;
import com.StarStudio.Utils.QueryPageUtils;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.Entity.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@RestController
@RequestMapping("/pb_goods")
@Api(tags = "抢购商品接口")
public class PanicBuyingGoodsController  {

    @Autowired
    PanicBuyingGoodsService panicBuyingGoodsService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    RedisService redisService;

    @Autowired
    PanicBuyingOrdersService panicBuyingOrdersService;

    /**
     * 带搜索条件分页查询（商家后台端）
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @GetMapping("/page")
    @ApiOperation("抢购商品分页接口 -> 支持条件检索，检索条件封装在抢购商品对象PanicBuyingGoods中。如需分页，必传pageNum和pageSize")
    public PageResult findPanicBuyingGoodsList(PanicBuyingGoods panicBuyingGoods){
        QueryPageUtils.startPage();
        PageInfo pageInfo;
        List<PanicBuyingGoods> panicBuyingGoodsList;
        long totalRecord;
        try {
            panicBuyingGoodsList = panicBuyingGoodsService.findPanicBuyingGoodsList(panicBuyingGoods);
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            if (sysUser.isAdmin()){
                totalRecord = panicBuyingGoodsService.findTotalRecord();
            }else {
                totalRecord = panicBuyingGoodsService.findStoreTotalRecord(sysUser.getUserId());
            }
            pageInfo = new PageInfo<>(panicBuyingGoodsList);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals(MessageConstant.USER_NO_EXIST)){
                return new PageResult(HttpStatusCode.ERROR, MessageConstant.USER_NO_EXIST);
            }
            return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_GOODS_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_GOODS_SUCCESS,pageInfo.getTotal(),panicBuyingGoodsList, totalRecord);
    }

    /**
     * 带搜索条件查询（APP端）
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @GetMapping("/list")
    @ApiOperation("抢购商品分页接口（APP端）-> 支持条件检索，检索条件封装在抢购商品对象PanicBuyingGoods中。如需分页，必传pageNum和pageSize")
    public Result findPanicBuyingGoodsResultList(PanicBuyingGoods panicBuyingGoods){
        List<PanicBuyingGoods> panicBuyingGoodsList;
        List<GoodsResult> list = null;
        try {
            panicBuyingGoodsList = panicBuyingGoodsService.findPanicBuyingGoodsList1(panicBuyingGoods);
            if (panicBuyingGoodsList.size() > 0){
                list = new ArrayList<>();
                for (PanicBuyingGoods pbGoods : panicBuyingGoodsList) {
                    GoodsResult goodsResult = new GoodsResult(goodsService.findByGoods_id(pbGoods.getGoods_id()),pbGoods);
                    if (new Timestamp(new Date().getTime()).before(pbGoods.getPanic_buying_start_time())){
                        goodsResult.setRemainBeginSeconds((int)((pbGoods.getPanic_buying_start_time().getTime() - new Date().getTime())/1000));
                        goodsResult.setRemainEndSeconds((int)((pbGoods.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }else if (new Timestamp(new Date().getTime()).after(pbGoods.getPanic_buying_end_time())) {
                        goodsResult.setRemainBeginSeconds(-1);
                        goodsResult.setRemainEndSeconds(-1);
                    }else {
                        goodsResult.setRemainBeginSeconds(0);
                        goodsResult.setRemainEndSeconds((int)((pbGoods.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }
                    list.add(goodsResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_GOODS_SUCCESS,list);
    }

    /**
     * 更新抢购商品信息
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @Log(title = "修改抢购商品", businessType = BusinessType.INSERT)
    @PutMapping
    @ApiOperation("抢购商品更新（修改）接口 -> 抢购商品ID、商品ID、抢购价格（鲜豆）、抢购商品库存数量、抢购开始时间、抢购结束时间、抢购状态不能为空")
    public Result updatePanicBuyingGoods(@RequestBody PanicBuyingGoods panicBuyingGoods){
        if (panicBuyingGoods == null || panicBuyingGoods.getPanic_buying_goods_id() == null || panicBuyingGoods.getGoods_id() == null ||
            panicBuyingGoods.getPanic_buying_price() == null || panicBuyingGoods.getPanic_buying_goods_stock() == null ||
            panicBuyingGoods.getPanic_buying_start_time() == null || panicBuyingGoods.getPanic_buying_end_time() == null || panicBuyingGoods.getPanic_buying_status() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            int i = panicBuyingGoodsService.updatePanicBuyingGoods(panicBuyingGoods);
            if (i > 0){
                // 将抢购商品库存更新到 Redis缓存中
                redisService.setCacheObject("panic_buying_goods:" + panicBuyingGoods.getGoods_id(),panicBuyingGoods.getPanic_buying_goods_stock());
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            if (e.getMessage().equals("库存不能小于零！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.STOCK_CAN_NOT_LESS_THAN_ZERO);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_PANIC_BUYING_GOODS_SUCCESS);
    }

    /**
     * 新增抢购商品
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @Log(title = "新增抢购商品", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("抢购商品新增接口 -> 商品ID、抢购价格（鲜豆）、抢购商品库存数量、抢购开始时间、抢购结束时间、抢购状态不能为空")
    public Result AddPanicBuyingGoods(@RequestBody PanicBuyingGoods panicBuyingGoods){
        if (panicBuyingGoods == null || panicBuyingGoods.getGoods_id() == null || panicBuyingGoods.getPanic_buying_price() == null
            || panicBuyingGoods.getPanic_buying_goods_stock() == null || panicBuyingGoods.getPanic_buying_start_time() == null
            || panicBuyingGoods.getPanic_buying_end_time() == null || panicBuyingGoods.getPanic_buying_status() == null){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            panicBuyingGoodsService.AddPanicBuyingGoods(panicBuyingGoods);
            // 将抢购商品库存更新到 Redis缓存中
            redisService.setCacheObject("panic_buying_goods:" + panicBuyingGoods.getGoods_id(),panicBuyingGoods.getPanic_buying_goods_stock());
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_PANIC_BUYING_GOODS_SUCCESS);
    }

    /**
     * 删除抢购商品
     * @param panic_buying_goods_ids 抢购商品ID数组（不是商品ID）
     * @return 结果对象 Result
     */
    @Log(title = "删除抢购商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{panic_buying_goods_ids}")
    @ApiOperation("抢购商品删除接口 -> path传抢购商品ID（不是商品ID）")
    public Result DeletePanicBuyingGoods(@PathVariable Long[] panic_buying_goods_ids){
        if (panic_buying_goods_ids == null || panic_buying_goods_ids.length == 0){
            return new Result(HttpStatusCode.BAD_REQUEST,MessageConstant.NOT_NULL_PARAMETER_ERROR);
        }
        try {
            for (Long panic_buying_goods_id : panic_buying_goods_ids) {
                panicBuyingGoodsService.DeletePanicBuyingGoods(panic_buying_goods_id);
                //获取对应商品ID
                Long goodsId = panicBuyingGoodsService.findGoodsIdByRecordId(panic_buying_goods_id);
                if (goodsId == null){
                    return new Result(HttpStatusCode.ERROR,MessageConstant.GOODS_NOT_EXIST);
                }
                // 删除Redis中抢购商品的缓存
                redisService.deleteObject("panic_buying_goods:" + goodsId);
                //删除Redis中抢购商品订单缓存
                List<Long> userIdList = panicBuyingOrdersService.findUserIdListByGoodsId(goodsId);
                if (!CollectionUtils.isEmpty(userIdList)){
                    for (Long userId : userIdList) {
                        redisService.deleteObject("panic_buying_goods_order:" + userId + ":" + goodsId);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_PANIC_BUYING_GOODS_SUCCESS);
    }

}
